#include <stdio.h>
#include <sys/sem.h>
#include <errno.h>
union semun{
    int val;
};

int operate(struct sembuf* buf,int num,int op,int flg){

}


int main(int argc,const char*  argv[]){

    key_t key = ftok("./app",'a');
    if(key < 0){
        perror("ftok err");
        return -1;
    }
    printf("%#x\n",key);

    int semid = semget(key,2,IPC_CREAT | IPC_EXCL | 0666);
    if(semid <= 0){
        if(errno == EEXIST){
            semid = semget(key,2,0666);
        }else{
            perror("semget err");
            return -1;
        }
    }else{
        union semun sem;
        sem.val=10;//设置资源量
        semctl(semid,0,SETVAL,sem);

        sem.val=0;
        semctl(semid,1,SETVAL,sem);
    }

    printf("semid:%d\n",semid);

    printf("%d\n",semctl(semid,0,GETVAL));
    printf("%d\n",semctl(semid,1,GETVAL));

    //PV操作
    struct sembuf buf;
    buf.sem_num=0;//信号灯编号
    buf.sem_op=-1;//申请资源
    buf.sem_flg = 0;//阻塞

    semop(semid,&buf,1);//对0号灯作申请资源

    buf.sem_num=1;//信号灯编号
    buf.sem_op=1;//申请资源
    buf.sem_flg = 0;//阻塞

    semop(semid,&buf,1);//对1号灯作申请资源

    printf("%d\n",semctl(semid,0,GETVAL));
    printf("%d\n",semctl(semid,1,GETVAL));

    //删除信号灯集
    semctl(semid,0,IPC_RMID); 


    return 0;
}